<?php
/**
 * 主要逻辑的附属类
 */
namespace app\workerman;
use app\common\entity\GameRoom;
use think\cache\driver\Redis;
use GatewayWorker\Lib\Gateway;
use app\index\model\User;
use app\common\entity\Mywallet;
use think\Db;




class Attached {
    protected  $config;
    protected  $redis;

    public function __construct()
    {
        //$this->config = Db::name('tto_config')->select();//ToConfig::ToGetAll();
        $config = Db::name('game_config')->select();//ToConfig::ToGetAll();

        $this->redis = new Redis();
        $this->redis->set('confog',json_encode($config));
    }



    /**
     * 获取某分组下的config
     * @param $group
     * @param $key
     * @return array
     */
    protected function getConfigGroup($group,$key = false){
        $config = json_decode($this->redis->get('confog'),true);
        $arr = [];
        foreach($config as $k=>$v){
            if($v['group'] == $group){
                $arr[] = $v;
                if($key !== false && $key === $v['key']){
                    return $v['value'];
                }
            }
        }
        return $arr;
    }

    /**
     * Gateway没有根据uid获取Clientinfo的接口，自定义一个
     */
    protected function getClientInfoByUid($uid){
        $ClientId = Gateway::getClientIdByUid($uid);

        if($ClientId == null)return false;
        $c_id = isset($ClientId[0])?$ClientId[0]:false;
        if(!Gateway::isOnline($c_id)){echo $c_id."\n";return;false;}

        $info = Gateway::getSession($c_id);
        return $info?$info:false;

    }

    protected function set_order_status($ordersn,$game_status){

    }
    /**
     * 获取用户头像和钱币
     * @param $uid
     */

    protected function getInfo($uid,$identity = 'user'){
		if($identity == 'user'){
			$user = new User();
			$userinfo = $user->getInfo($uid);
			;
			$money = MyWallet::where('user_id',$uid)->find();

			//$ratio = Quotation::where('id',1)->find();
			if ($userinfo && $money){
				$data = [
					'uid'       =>  $uid,
					'avatar'    =>$userinfo['avatar'],
					'nick_name' =>$userinfo['nick_name'],
				/*	'btc'       =>$money['btc'],
					'eth'       =>$money['eth'],
					'eos'       =>$money['eos'],
					'usdt'      =>round($money['btc']/$ratio['btc']+$money['eth']/$ratio['eth']+$money['eos']/$ratio['eos'],2),
                    'number'    =>$money['number']*/
				];
				return  $data;

			}
		}else if($identity == 'tourist'){
			$userinfo = Db::name('tourist')->where('tourist_id',$uid)->find();
			if ($userinfo ){
				$data = [
					'uid'       =>  $uid,
					'avatar'    =>$userinfo['avatar'],
					'nick_name' =>$userinfo['nick_name'],
					'usd'       =>$userinfo['usd'],
					'usdt'      =>$userinfo['usd']
				];
				return  $data;
			}
		}
        
        return false;
    }

    /**
     * 获取房间的用户List
     * @param $group
     * @return bool
     */
    protected function getUserListByGroup($group){
        $clients = Gateway::getClientSessionsByGroup($group);
        if(!$clients)return false;
        $uids = implode(',',array_column($clients,'uid'));
		
		$gArr = explode('_',$group);
		$room_id = $gArr[1];
		if($room_id == 1){
			$userList = Db::name('tourist')->where('tourist_id','in',$uids)->select();
			if(!$userList)return false;
			foreach($userList as $k=>$v){
				$userList[$k]['usdt'] = $v['usd'];
				$userList[$k]['uid'] = $v['tourist_id'];
			}
			return $userList;
		}else if($room_id >1){
			$userModwl = new User();
			$userList = $userModwl->where('id','in',$uids)->select()->toArray();
			if(!$userList)return false;
			$moneyList = MyWallet::where('user_id','in',$uids)->select()->toArray();
			$ratio = Quotation::where('id',1)->find();
			$arr = [];

			foreach($userList as $k=>$v){
				foreach($moneyList as $key=>$val){
					if($v['id'] == $val['user_id']){
						$arr[] = [
							'uid'           =>$v['id'],
							'avatar'        =>$v['avatar'],
							'nick_name'     =>$v['nick_name'],
							'btc'           =>$val['btc'],
							'eth'           =>$val['eth'],
							'eos'           =>$val['eos'],
							'usdt'          =>round($val['btc']/$ratio['btc']+$val['eth']/$ratio['eth']+$val['eos']/$ratio['eos'],2),
                            'number'        =>$val['number'],
						];
					}
				}
			}
			return $arr;
		}
    }

    /**
     * 写入缓存
     * @access public
     * @param  string            $name 缓存变量名
     * @param  string            $key 缓存键名
     * @param  mixed             $value  存储数据
     * @return boolean
     */
    public function redisSet($name,$key,$value){
        $this->redis->hSet($name, $key,$value);
        return $this->redis->hGet($name, $key);
    }
    /**
     * 哈希自增缓存（针对21点桌子）
     * @access public
     * @param  string    $name 缓存变量名
     * @param  string    $key 缓存键名
     * @param  int       $step 步长
     * @return false|int
     */
    public function redisInc($name,$key,$step = 1){
        $num = $this->redis->hGet($name, $key);
        $this->redis->hSet($name, $key,$num + $step);
        return $this->redis->hGet($name, $key);
    }
    /**
     * 自减缓存（针对数值缓存）
     * @access public
     * @param  string    $name 缓存变量名
     * @param  int       $step 步长
     * @return false|int
     */
    public function redisDec($name,$key,$step = 1){
        $num = $this->redis->hGet($name, $key);
        $this->redis->hSet($name, $key,($num - $step));
        return $this->redis->hGet($name, $key);
    }


    //获取币种支付数量
    public function getPayNum($uid,$usdt,$pay1,$pay2,$pay3,&$arr=[]){
        $ratio = Quotation::where('id',1)->find();
        $wallet = MyWallet::where('user_id',$uid)->find();

        if(floor($wallet[$pay1]/$ratio[$pay1]) >= $usdt){
            $arr = [$pay1=>round($usdt*$ratio[$pay1],8),$pay2=>0,$pay3=>0];
            return $arr;
        }else{
            $over_usdt = $usdt - floor($wallet[$pay1]/$ratio[$pay1]);
            if(floor($wallet[$pay2]/$ratio[$pay2]) >= $over_usdt){
                $arr = array(
                    $pay1 => round(floor($wallet[$pay1]/$ratio[$pay1]) * $ratio[ $pay1 ],8) ,
                    $pay2 => round($over_usdt*$ratio[$pay2],8) ,
                    $pay3 => 0
                );
                return $arr;
            }else{
                $overover_usdt = $usdt - floor($wallet[$pay1]/$ratio[$pay1])-floor($wallet[$pay2]/$ratio[$pay2]);
                $arr = array(
                    $pay1 => round(floor($wallet[$pay1]/$ratio[$pay1]) * $ratio[ $pay1 ],8) ,
                    $pay2 => round(floor($wallet[$pay2]/$ratio[$pay2]) * $ratio[ $pay2 ],8),
                    $pay3 => round($overover_usdt*$ratio[$pay3],8)
                );
                return $arr;
            }
        }
    }



    public function setTableStatus($room_id,$table_id,$status){
        $tables = json_decode($this->redis->hGet("tto_player_table",$room_id),true);
        $thiskey = -1;
        foreach($tables as $k=>$v){
            if($v['table_id'] == $table_id){
                if( $tables[$k]['status'] == $status){return;}
                $tables[$k]['status'] = $status;
            }
        }
        $this->redis->hSet("tto_player_table",$room_id,json_encode($tables));
        $roominfo = Db::name('tto_room')->where(['room_id'=>$room_id])->value('user_id');
        Gateway::sendToGroup('room_id_'.$room_id,successSend('tablechange','桌子变动',['uid'=>$roominfo,'table'=>$tables]));
        if($status != 3){
            Gateway::sendToGroup('table_'.$room_id.'_'.$table_id['table_id'],successSend('tableInChange','桌子变动',['changeIndex'=>$thiskey,'uid'=>$roominfo,'table'=>json_decode($this->redis->hGet('tto_player_table',$room_id),true)]));
        }
    }


    static protected function get_award($room_id,$arr,$room_num,$number = 0){
        if(empty($arr))return;
        $roomInfo = GameRoom::where('id',$room_id)->find();
        $is_oobot = false;
        foreach($arr as $k=>$v){
            $arr[$k]['award'] = 0;
            if($v['robot'] == 1){
                $is_oobot = true;
            }
        }

        $keys = array_rand($arr,1);

//        shuffle($arr);



        $user = \app\common\entity\User::where('id',$arr[$keys]['uid'])->find();

        if($number <= 50){
            if(($is_oobot && $room_num === 1 && $arr[$keys]['robot'] == 0) || ($room_num === 2 && $arr[$keys]['robot'] == 1)){
                $number++;
                return self::get_award($room_id,$arr,$room_num,$number);
            }
        }


        $out = [
            'uid'=>$arr[$keys]['uid'],
            'nick_name'=>$user['nick_name']
        ];




        foreach($arr as $k=>$v){
            if($v['uid'] == $out['uid']){
                $arr[$k]['status'] = 2;
            }
        }
        return ['arr'=>$arr,'out'=>$out];
    }


    /**
     * 将数组存到redis哈希里
     * @param $name
     * @param $key
     * @param $value
     * @return array
     */
    public function redis_hSet($name,$key,$value){
        return $this->redis->hSet($name,$key,json_encode($value));
    }

    /**
     * 返回redis的哈希并转成数组返回
     * @param $name
     * @param $key
     * @return mixed
     */
    public function redis_hGet($name,$key){
        return json_decode($this->redis->hGet($name,$key),true);
    }

    /**
     * 删除哈希类型redis
     * @param $name
     * @param $key
     * @return mixed
     */
    public function redis_hDel($name,$key){
        return $this->redis->hDel($name,$key);
    }

    /**
     * 奖数字瓜分为$div份
     * @param $div
     * @param $total
     * @return array
     */
    static public function randomDivInt($div,$total){
        $remain=$total*100;
        $max_sum=($div-1)*$div/2;
        $p=$div; $min=0;
        $a=array();
        for($i=0; $i<$div-1; $i++){
            $max=($remain-$max_sum)/($div-$i);
            $e=rand($min,$max);
            $min=$e+1; $max_sum-=--$p;
            $remain-=$e;
            $a[$e]=true;
        }
        $a=array_keys($a);
        $a[]=$remain;
        foreach($a as $k=>$v){
            $a[$k] = bcmul($v,0.01,4);
        }
        return $a;
    }

    public function  roomchange(){
        //发送房间更
        $users = Gateway::getAllClientIdList();

        foreach($users as $key=>$val){

            $session = Gateway::getSession($val);
            if(isset($session['ordersn'])){
                $orderMoney = Db::name('shop_order')->where('ordersn',$session['ordersn'])->sum('total');


                $arrr = GameRoom::where('money',$orderMoney)->select();
                foreach($arrr as $k=>$v){
                    $the_room = $this->redis_hGet('1225blz_roominfo',$v['id']);

                    $v['count'] = isset($the_room['users'])?count($the_room['users']):0;
                }

                Gateway::sendToClient($val,successSend('roomchange','房间变更2',toArray($arrr)));
            }

        }
    }



    public function videoToHtml($src){
        
    }
}